<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import useService from './service'
  import { ref } from 'vue'
  import { GetRechargeRecordsParam, RechargeRecord } from './types'
  import DateRange from '@/components/DateRange.vue'
  import { ElMessage } from 'element-plus'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import { RefreshRight } from '@element-plus/icons-vue'

  const props = defineProps({
    factoryId: {
      type: String,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'loading-change', value: boolean): void
  }>()

  // 筛选条件
  const filter = ref<GetRechargeRecordsParam>({
    createOrderEndTime: '',
    createOrderStartTime: '',
    keyword: '',
    rechargeEndTime: '',
    rechargeStartTime: '',
    limit: 50,
    page: 1,
    mode: null,
    status: null,
  })

  // 充值方式选项
  const modeOptional = [
    { value: 1, label: '支付宝' },
    { value: 2, label: '微信' },
    { value: 3, label: '银联' },
    { value: 4, label: '对公支持' },
    { value: 5, label: '平台调整' },
  ]

  // 充值状态选项
  const statusOptional = [
    { value: 1, label: '待支付' },
    { value: 2, label: '已支付' },
    { value: 3, label: '已取消' },
  ]

  // 分页组件实例
  const paginationRef = ref<InstanceType<typeof Pagination> | null>(null)

  // 使用服务
  const { total, get } = useService

  // 获取filter
  const getFilter = (): GetRechargeRecordsParam => {
    const result = { ...filter.value }

    if (paginationRef.value) {
      result.limit = paginationRef.value.size
      result.page = paginationRef.value.current
    }

    return result
  }

  const isStartDateGreaterThanEndDate = ref(false)

  // 表格数据
  const tableData = ref<Array<RechargeRecord>>([])

  // 获取列表方法
  const getList = async () => {
    if (isStartDateGreaterThanEndDate.value) {
      ElMessage({
        type: 'error',
        message: '订单创建开始时间不能大于结束时间',
      })
      return
    }
    emits('loading-change', true)
    try {
      tableData.value = await get(getFilter(), props.factoryId)
    } catch (errMsg) {
      ElMessage({
        type: 'error',
        message: errMsg,
        showClose: true,
      })
    }
    emits('loading-change', false)
  }

  // 订单创建日期更新事件
  const handleOrderCreateDateChange = (param: {
    startDate: string
    endDate: string
    isStartDateGreaterThanEndDate: boolean
  }) => {
    filter.value.createOrderStartTime = param.startDate
    filter.value.createOrderEndTime = param.endDate
    isStartDateGreaterThanEndDate.value = param.isStartDateGreaterThanEndDate
    if (param.isStartDateGreaterThanEndDate) {
      ElMessage({
        type: 'error',
        message: '订单创建开始时间不能大于结束时间',
      })
    }
  }

  // 订单创建日期范围组件实例
  const orderCreateDateRangeRef = ref<InstanceType<typeof DateRange> | null>(null)

  // 重置事件
  const handleReset = () => {
    if (orderCreateDateRangeRef.value) {
      orderCreateDateRangeRef.value.resetDateRange()
      isStartDateGreaterThanEndDate.value = false
    }
    Object.assign(filter.value, {
      createOrderEndTime: '',
      createOrderStartTime: '',
      keyword: '',
      rechargeEndTime: '',
      rechargeStartTime: '',
      limit: 50,
      page: 1,
      mode: null,
      status: null,
    })
    getList()
  }

  // 按钮取消聚焦事件
  const handleCancelFocus = (e: Event) => {
    (e.target as HTMLButtonElement).blur()
  }

  defineExpose({
    getList,
  })
</script>

<template>
  <div class="recharge_record">
    <div class="filter">
      <!--充值方式-->
      <el-select style="width: 140px" @change="getList" placeholder="请选择充值方式" v-model="filter.mode">
        <el-option
          v-for="item in modeOptional"
          :key="item.label"
          :label="item.label"
          :value="item.value"
        />
      </el-select>

      <!--充值状态-->
      <el-select style="width: 140px" placeholder="请选择充值状态" @change="getList" v-model="filter.status">
        <el-option
          v-for="item in statusOptional"
          :key="item.label"
          :label="item.label"
          :value="item.value"
        />
      </el-select>

      <!--订单创建时间-->
      <DateRange
        start-date-placeholder="创建开始时间"
        end-date-placeholder="创建结束时间"
        @change="handleOrderCreateDateChange"
        ref="orderCreateDateRangeRef"
        width="16vw"
        class="date_range"
      />

      <!--订单号-->
      <el-input style="width: 8vw !important" @keyup.enter="getList" @clear="getList" v-model="filter.keyword" placeholder="订单号" />

      <!--按钮组-->
      <div class="btn_group">
        <HButton type="primary" @focus="handleCancelFocus" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
        <HButton @click="handleReset" @focus="handleCancelFocus">
          <el-icon>
            <RefreshRight />
          </el-icon>
          重置
        </HButton>
      </div>
    </div>

   <div class="table">
    <el-table :border="true" stripe resizable :data="tableData" style="position: absolute" height="100%">
      <template #empty>
        <el-empty description="暂无数据" />
      </template>

      <!--序号-->
      <el-table-column label="序号" type="index" width="50" align="center" />

      <!--订单号-->
      <el-table-column show-overflow-tooltip prop="code" label="订单号" width="350" />

      <!--商家名称-->
      <el-table-column show-overflow-tooltip prop="factory" label="商家名称" width="100" />

      <!--充值金额-->
      <el-table-column show-overflow-tooltip prop="money" label="充值金额" width="100" />

      <!--充值时间-->
      <el-table-column show-overflow-tooltip label="充值时间" prop="paymentTime" width="128" />

      <!--充值状态-->
      <el-table-column show-overflow-tooltip prop="status" label="充值状态" width="80">
        <template #default="scope">
          <div>
            <HStatus v-if="scope.row.status === 1" type="warning">待支付</HStatus>
            <HStatus v-else-if="scope.row.status === 2" type="success">已支付</HStatus>
            <HStatus v-else type="info">已取消</HStatus>
          </div>
        </template>
      </el-table-column>

      <!--充值方式-->
      <el-table-column show-overflow-tooltip prop="mode" label="充值方式" width="100">
        <template #default="scope">
          <div>
            <span v-if="scope.row.mode === 1">支付宝</span>
            <span v-else-if="scope.row.mode === 2">微信</span>
            <span v-else-if="scope.row.mode === 3">银联</span>
            <span v-else-if="scope.row.mode === 4">对公支持</span>
            <span v-else>平台调整</span>
          </div>
        </template>
      </el-table-column>

      <!--是否申请发票-->
      <el-table-column show-overflow-tooltip prop="applyInvoice" label="是否申请发票" width="100">
        <template #default="scope">
          <div>
            <HStatus v-if="scope.row.applyInvoice" type="success">已申请</HStatus>
            <HStatus v-else type="info">未申请</HStatus>
          </div>
        </template>
      </el-table-column>
    </el-table>
   </div>

    <!--分页-->
    <div class="recharge_record_pagination">
      <Pagination
        ref="pageRef"
        :list_total="total"
        @size-change="getList"
        @current-change="getList"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
  .recharge_record {
    height: 100%;
    display: flex;
    flex-direction: column;
    gap: 12px;

    .filter {
      display: flex;
      gap: 5px;
      align-items: center;
      justify-content: flex-end;

      .btn_group {
        display: flex;
        gap: 5px;

        .search_btn,
        .reset_btn {
          width: 3.2vw;
          margin: 0;
          height: 28px;
          border-radius: 2px !important;
        }
      }

      .date_range {
        :deep(.el-input__wrapper) {
          height: 26px !important;
        }
      }
    }
    .table {
          margin-top: 0 !important;
          flex: 1;
          position: relative;
    }
    .recharge_record_pagination {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
